package com.ccc.netty.upload.server;

import com.ccc.netty.upload.server.handler.DecodeHandler;
import com.ccc.netty.upload.server.handler.TcpServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TcpServer {
	
	public static void main(String[] args) {
		new TcpServer().start();
	}

	/**
	 * TODO 启动服务
	 */
	public void start() {

		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		ServerBootstrap bootstrap = new ServerBootstrap();
		bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY, true).handler(new LoggingHandler(LogLevel.INFO))
				.childHandler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						
						ch.pipeline().addLast(
								// 自定义解码器
								new DecodeHandler(),
								new StringEncoder(CharsetUtil.UTF_8),
								// 自定义的文件处理handler
								new TcpServerHandler());
					}
				});

		try {
			int port = 8888;
			String host = "127.0.0.1";

			ChannelFuture future = bootstrap.bind(host, port).sync();

			log.info("启动服务器 端口[{}]", port);

			future.channel().closeFuture().sync();

		} catch (InterruptedException e) {
			log.error("%s", e);
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
